package com.cenxi.common.aspect.annotation;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cenxi.dao.domain.AccountRole;
import com.cenxi.dao.domain.Menu;
import com.cenxi.dao.domain.RoleMenu;
import com.cenxi.dao.service.AccountRoleService;
import com.cenxi.dao.service.MenuService;
import com.cenxi.dao.service.RoleMenuService;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author cenxi
 * @Date 2023/5/12 17:09
 * @Version 1.0
 */
@Component
@Slf4j
public class PermissionsService {
    @Autowired
    private AccountRoleService cxAccountRoleService;
    @Autowired
    private RoleMenuService cxRoleMenuService;
    @Autowired
    private MenuService cxMenuService;

    /**
     * 校验用户有操作权限没有
     * @param userId
     * @param permissions
     * @return
     */
    public Boolean Authentication(String userId, String permissions) {
        List<Long> roleIds = cxAccountRoleService.list(new LambdaQueryWrapper<AccountRole>()
                .eq(AccountRole::getAccountId, userId)).stream().map(AccountRole::getRoleId).collect(Collectors.toList());
        List<Long> menuIds = cxRoleMenuService.list(new LambdaQueryWrapper<RoleMenu>()
                .in(RoleMenu::getRoleId, roleIds)).stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        List<Menu> CxMenus = cxMenuService.list(new LambdaQueryWrapper<Menu>()
                .in(Menu::getId, menuIds));
        log.info("当前id为: {}, 权限有: {}", userId, CxMenus.stream().
                map(Menu::getPerms).
                filter(Objects::nonNull).
                collect(Collectors.toList()));
        return Collections.isEmpty(CxMenus.stream().filter(item -> permissions.equals(item.getPerms())).collect(Collectors.toList()));
    }
}
